package org.qu.userdao.action;

import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;
import org.qu.factory.DaoFactory;
import org.qu.util.MailUtil;
import org.qu.util.StringUtils;
import org.qu.util.ThreeDes;
import org.qu.util.dao.ConnectionData;
import org.qu.vo.IsnsRegisterTemp;
import org.qu.vo.IsnsUsers;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UserManager extends ActionSupport {
	private IsnsUsers user;
	private boolean flag = false;
	private String code; // 验证码
	private String id;  //邮件 返回的id
	private String email;  //邮件返回

	/**
	 * AJAX验证邮箱是否重复
	 * 
	 * @return
	 * @throws Exception
	 */
	public String isEmail() throws Exception {
		System.out.println(this.user.getUserEmail());
		if (user != null && user.getUserEmail() != null) {

			flag = DaoFactory.factoryUserDao(new ConnectionData().getConnection()).isEmail(user.getUserEmail());
			if(flag=true){ //验证临时表是否存在邮箱
				flag = DaoFactory.factoryUserDao(new ConnectionData().getConnection()).isRegisterTempEmail(user.getUserEmail()); 
			}

		}
		JSONObject json = new JSONObject();

		json.put("flag", flag);
		HttpServletResponse response = ServletActionContext.getResponse();

		response.setCharacterEncoding("gbk");

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();

		out.print(json);

		out.close();

		return null;
	}

	/**
	 * AJAX验证码验证
	 * 
	 * @return
	 * @throws Exception
	 */
	public String isCode() throws Exception {
		System.out.println(this.code);
		String rand = ServletActionContext.getRequest().getSession()
				.getAttribute("rand").toString();

		if (rand != null && !"".equals(rand) && code != null
				&& !"".equals(code)) {

			flag = rand.equalsIgnoreCase(code) ? true : false;

		}

		JSONObject json = new JSONObject();
		json.put("flag", flag);
		HttpServletResponse response = ServletActionContext.getResponse();

		response.setCharacterEncoding("gbk");

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();

		out.print(json);

		out.close();
		return Action.SUCCESS;
	}

	/**
	 * 用户注册发送邮件进行确认
	 * 
	 * @return
	 */
	public String register() throws Exception {

		if (user != null) {

			MailUtil mail = new MailUtil();
			// 将此用户信息插入到临时表中
			IsnsRegisterTemp temp = new IsnsRegisterTemp();

			temp.setUserName(user.getUserName());

			temp.setUserPwd(user.getUserPws());

			temp.setEmail(user.getUserEmail());

			temp.setSex(user.getUserSex());

			temp.setCreateDate(new Date());

			if (DaoFactory.factoryUserDao(new ConnectionData().getConnection())
					.doCreateRegisterTemp(temp)) {
				//创建成功则把刚刚创建的用户id取出
				IsnsRegisterTemp ttRegisterTemp=DaoFactory.factoryUserDao(new ConnectionData().getConnection()).isRegisterTemp(temp.getEmail(), temp.getUserPwd());
				
				//查询出来
				if(ttRegisterTemp!=null){
					String idString=new StringUtils().encrypt(ttRegisterTemp.getId()+"");
					String emailtemp=new StringUtils().encrypt(ttRegisterTemp.getEmail());
					mail
					.send(
							"hanjin7278@126.com",
							"信息核实,请点击&nbsp;&nbsp;"
									+ "<a  href='http://127.0.0.1"
									+ ServletActionContext.getRequest()
											.getContextPath()
									+ "/UserManager/user!registerCallBack.action?id="
									+ idString + "&email="+emailtemp+"  target='_blank'>核实</a>&nbsp;<br/>如果没有跳转请复制地址到浏览器中 http://127.0.0.1"
									+ ServletActionContext.getRequest()
											.getContextPath()
									+ "/UserManager/user!registerCallBack.action?id="
									+ idString+"&email="+emailtemp,user.getUserEmail());
					
				}

			}

		}

		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("userMail", user.getUserEmail());
		return "welcome";
	}

	/**
	 * 从邮箱中确认返回的信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String registerCallBack() throws Exception {  //临时表数据是否存在取决于:激活删除，过期删除

		if (id!=null && email!=null) {
			int temid=Integer.parseInt(new StringUtils().decrypt(id));
			
			String temp=email.substring(0,email.indexOf(" "));
			
			String tempemail=new StringUtils().decrypt(temp.trim());
			// 查询临时表中人员信息是否存在
			IsnsRegisterTemp tt = DaoFactory.factoryUserDao(
					new ConnectionData().getConnection()).isRegisterTemp(temid,tempemail);
			// 临时表中此人存在
			if (tt != null) {
				 flag  = false;
				IsnsUsers isnsUsers = new IsnsUsers();
				isnsUsers.setUserEmail(tt.getEmail());
				isnsUsers.setUserPws(tt.getUserPwd());
				isnsUsers.setUserName(tt.getUserName());
				isnsUsers.setUserSex(tt.getSex());
				// 将临时表中的人员信息添加到isns_user表中
				DaoFactory.factoryUserDao(new ConnectionData().getConnection())
						.register(isnsUsers);
				// 保存之后删除临时表中的数据
				DaoFactory.factoryUserDao(new ConnectionData().getConnection())
						.removeIsRegisterTemp(tt.getId());
				// 删除之后将此人信息保存在session中
				ServletActionContext.getRequest().getSession().setAttribute(
						"user", isnsUsers);
				return "module";

			}else { // 如果此人在临时表中不存在则直接查询此人信息返回此人的个人中心页面
				flag = DaoFactory.factoryUserDao(new ConnectionData().getConnection()).isEmail(user.getUserEmail());
			}
		}
		if(flag = true){ //用户已激活跳转到登录页面
			 return "login";
		 }else{ //注册已过期跳转到提示注册页面
			return "registerExpired";
		 }
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public IsnsUsers getUser() {
		return user;
	}

	public void setUser(IsnsUsers user) {
		this.user = user;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
}
